
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}
function createTree(arr) {
  if(arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}
function preShow(node) {
  if(node == null)
    return ;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function(root) {
  root = createTree(root);
  let result = [];
  function levelTraversal(root) {
    let queue = [{
      node: root,
      level: 0
    }], stack = [], arr = [];
    while(queue.length > 0 || stack.length) {
      let obj;
      if(queue.length) {
        obj = queue[0]
      } else {
        queue = stack.reverse();
        continue;
      }
      queue.splice(0, 1);
      if(obj.node == null)
        continue;
      if(arr[obj.level]) {
        arr[obj.level].push(obj.node.val);
      } else {
        arr[obj.level] = [obj.node.val];
      }
      queue.push({
        node: obj.node.left,
        level: obj.level + 1
      });
      queue.push({
        node: obj.node.right,
        level: obj.level + 1
      });

    }
    return arr;
  }
  result = levelTraversal(root);
  for(let i = 0; i < result.length; i++) {
    if(i % 2 == 1)
      result[i] = result[i].reverse();
  }
  return result;
};
let root = [3,9,20,null,null,15,7];
console.log(zigzagLevelOrder(root));
root = [1];
console.log(zigzagLevelOrder(root));
root = [];
console.log(zigzagLevelOrder(root));
root = [1,2,3,4,null,null,5];
console.log(zigzagLevelOrder(root));
root = [0,2,4,1,null,3,-1,5,1,null,6,null,8];
console.log(zigzagLevelOrder(root));
